package com.simpleim.starter.handler;

import com.simpleim.common.task.FutureTaskScheduler;
import com.simpleim.im.common.bean.msg.ProtoMsg;
import com.simpleim.starter.processor.ChatRedirectProcesser;
import com.simpleim.starter.server.ServerSession;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@ChannelHandler.Sharable
public class ChatRedirectHandler extends ChannelInboundHandlerAdapter {

    private static final Logger LOGGER = LoggerFactory.getLogger(ChatRedirectHandler.class);

    @Autowired
    private ChatRedirectProcesser processer;

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (!(msg instanceof ProtoMsg.Message)) {
            super.channelRead(ctx, msg);
            return;
        }

        ProtoMsg.Message message = (ProtoMsg.Message) msg;
        ProtoMsg.HeadType headType = message.getType();
        if (!(headType == ProtoMsg.HeadType.MESSAGE_REQUEST)) {
            super.channelRead(ctx, msg);
            return;
        }

        // 先判断自己是否登录，如果没有登录，不能发送消息
        ServerSession session = ctx.attr(ServerSession.KEY_SESSION).get();
        if (session == null || !session.isLogin()) {
            LOGGER.error("用户尚未登录，不能发送消息");
            return;
        }
        FutureTaskScheduler.add(() -> {
            processer.action(session, message);
        });
    }
}
